package com.facebookproject.graph.element;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import static com.facebookproject.Const.*;
public class LoadImageTask extends AsyncTask<URL, Void, Bitmap>{
	String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH + APP_PHOTO;
	Context context;
	private ViewHolder holder;
	public LoadImageTask(ViewHolder holder,Context context) {
		this.holder = holder;
		this.context = context;
	}
	@Override
	protected Bitmap doInBackground(URL... imgURL) {
		if(isCancelled())return null;
		Bitmap bmp = null;
		try {
			bmp = BitmapFactory.decodeStream(imgURL[0].openConnection().getInputStream());
			try {
				File dir = new File(fullPath);
				if (!dir.exists()) 
					dir.mkdirs();
				OutputStream fOut = null;
				File file = new File(fullPath, "profilespictures_" + holder.id +".jpg");
				if(!file.exists())
					file.createNewFile();
				fOut = new FileOutputStream(file);
				bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
				fOut.flush();
				fOut.close();
			} catch (Exception e) {
				Log.e("saveToExternalStorage()", e.getMessage());
			}
			return bmp;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	protected void onPreExecute() {
		String img_preload = fullPath + "/profilespictures_" + holder.id +".jpg";
		File check_exists = new File(fullPath, "profilespictures_" + holder.id +".jpg");
		if(check_exists.exists()){
			holder.progress.setVisibility(View.GONE);
			holder.img.setVisibility(View.VISIBLE);
			Bitmap bmp_preload = BitmapFactory.decodeFile(img_preload);
			if(bmp_preload!=null)
				holder.img.setImageBitmap(bmp_preload);
			else{
				holder.img.setVisibility(View.GONE);
				holder.progress.setVisibility(View.VISIBLE);
			}
		}else{
			holder.img.setVisibility(View.GONE);
			holder.progress.setVisibility(View.VISIBLE);
		}
		super.onPreExecute();
	}

	@Override	
	protected void onPostExecute(Bitmap result) {
		int pos = Integer.parseInt(holder.img.getTag().toString());
		if(holder.position==pos&&result!=null){
			holder.progress.setVisibility(View.GONE);
			holder.img.setVisibility(View.VISIBLE);
			holder.img.setImageBitmap(result);
			
			
		}
		super.onPostExecute(result);
	}
}  

